package com.siecom.module;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import com.TcFingerClient.TcFingerClientApi;
import com.example.dmtprotocollib.DmtProtocol;
import com.example.dmtprotocollib.DmtSPIProcess;
import com.fingerUsb.Callback;
import com.fingerUsb.FingerResult;
import com.fingerUsb.OnConnectListener;
import com.fingerUsb.USBComm;
import com.siecom.algorithm.sm.SM2keyPair;
import com.siecom.algorithm.sm.SMUtil;
import com.siecom.algorithm.util.Arrays;
import com.siecom.constconfig.ConstDefine;
import com.siecom.constconfig.ErrorDefine;
import com.siecom.framework.bean.BankCardInfoBean;
import com.siecom.framework.bean.TradeLogBean;
import com.siecom.framework.device.SiecomDevice;
import com.siecom.framework.device.SiecomTask;
import com.siecom.framework.module.BankCardModule;
import com.siecom.hostservice.MainActivity;
import com.siecom.nativelibs.rkGpioControlNative;
import com.siecom.tool.ByteTool;
import com.siecom.tool.LogUtil;
import com.siecom.tool.MacUtils;
import com.siecom.tool.StringUtil;
import com.siecom.tool.Timer;
import com.siecom.transport.bluetooth.BlueServer;
import com.techshino.fp.util.FpCoder;
import com.techshino.fp.util.SerialPortUtil;
import com.techshinogongjian.fp.client.TcFingerClient;
import com.techshinogongjian.fp.util.FpConfig;
import com.techshinogongjian.fp.util.FpConst;
import com.techshinogongjian.fp.util.USBUtil;
import com.wellcom.finger.FpDriverV22;
import com.zz.finger.FingerDevice;

import org.json.JSONException;
import org.json.JSONObject;
import org.zz.jni.zzFingerAlg;
import org.zz.mxhidfingerdriver.MXFingerDriver;
import org.zz.protocol.MXVersion;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static android.content.Context.MODE_PRIVATE;
import static com.siecom.constconfig.ConstDefine.KEY_3DES;
import static com.siecom.constconfig.ConstDefine.KEY_NOENCRYPTION;
import static com.siecom.constconfig.ConstDefine.KEY_SM;


/**
 * Created by zhq on 2016/6/24.
 */
public class DeviceInterface {

    public static Bitmap fingerImage = null;
    static {
        //GPIO
//        rkGpioControlNative.init();

    }

    public final static String NO_ENCRYPTION = "10";
    public final static String THREE_DES_MODE = "30";
    public final static String DES_MODE = "20";
    public final static String DES_MODE_MAIN = "70";
    public final static String SM4_MODE = "80";
    public final static String SM4_MODE_MAIN = "90";

    public final static String TAG = "DeviceInterface";

    public static IDCardModule identityModule = IDCardModule.getInstance();
    public static CipherKeyBoardModule keyBoardModule = CipherKeyBoardModule.getInstance();
    public static FinancialModule financialModule = FinancialModule.getInstance();
    public static TesoFingerprintModule tesoFingerPrintModule = TesoFingerprintModule.getInstance();

    public static final String sBmpFile = Environment.getExternalStorageDirectory() + "/finger_wl.bmp";

    public static CallBackHandler handler = new CallBackHandler();


    /**
     * 模块独立线程池所有操作通过线程池保证先入先出
     */
    private static ExecutorService wellThreadPool = Executors.newFixedThreadPool(1);

    private static ExecutorService finanThreadPool = Executors.newFixedThreadPool(1);

    private static ExecutorService keyThreadPool = Executors.newFixedThreadPool(1);

    private static ExecutorService fingerThreadPool = Executors.newFixedThreadPool(1);

    private static ExecutorService idThreadPool = Executors.newFixedThreadPool(1);

    private static ExecutorService DmtThreadPool = Executors.newFixedThreadPool(1);

    private static DmtSPIProcess dmtTest = new DmtSPIProcess();


    private static USBComm mUsbUtil;
    private static TcFingerClient mClient;
    private static MXFingerDriver zzClient;


    /**
     * 各模块均为单线程，会先终结当前线程再起
     */

    public static FingerPrintRunnable fingerPrintRunnable = null;
    public static IdentityRunnable identityRunnable = null;
    public static KeyBoardRunnable keyBoardRunnable = null;
    private static FinancialRunnable financialRunnable = null;

    public static KeyInputRunnable keyInputRunnable = null;

    private final static int START = 0;
    private final static int SUCCESS = 1;
    private final static int ERROR = 2;
    private final static int COMPLETED = 3;

    private static volatile boolean INIT_SIGN = false;

    private static byte[] cipherData = new byte[102400];
    private static int retryTimes = 0;

    public static int isEncrypted = 0;
    SerialPortUtil mSerialPortUtil;
    private static String mPortPath = "/dev/ttyMT1";
    private static int mBaudrate = 9600;

    private com.techshino.fp.client.TcFingerClient mTcFingerClient;
    private Context mContext;
    private static byte[] mTemplate;

    public static TcFingerClientApi mTcFingerClientApi;

    public static enum Result {

        START, SUCCEED, ERROR, COMPLETED

    }


    public static void InitFinger(){
        if(Build.MODEL.equals("A108Plus")) TcFingerClientApi.gpio_control(100, 1);
        if(!TcFingerClientApi.gpio_read(124)){
            TcFingerClientApi.gpio_control(124, 1);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        SharedPreferences setting = PreferenceManager
                .getDefaultSharedPreferences(MainActivity.context);
//        String device = setting.getString("DEVICE", "");
////        int baudrate = Integer.parseInt(setting.getString("BAUDRATE", "0"));
//        mPortPath = device;
//        mBaudrate = baudrate;

//        Log.i("SerialPort", "device:"+device);


//		ToastUtils.showToast(this, "path:" + mPortPath + " baud:" + mBaudrate);

        mTcFingerClientApi = new TcFingerClientApi(MainActivity.context);
        mTcFingerClientApi.DLL_OpenDevice(mPortPath, mBaudrate);
        mTcFingerClientApi.clear();
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }

    public static int light = 0;

    public static void lightOff() {
//        MainActivity.getmSys().DLL_SysLedControl((byte) 0,(byte)0);//键盘
//        MainActivity.getmSys().DLL_SysLedControl((byte) 1,(byte)0);//指纹
//        MainActivity.getmSys().DLL_SysLedControl((byte) 2,(byte)0);//IC
//        MainActivity.getmSys().DLL_SysLedControl((byte) 3,(byte)0);//磁条卡
//        MainActivity.getmSys().DLL_SysLedControl((byte) 4,(byte)0);//蓝牙
//        MainActivity.getmSys().DLL_SysLedControl((byte) 5,(byte)0);//身份证

    }

    public static void lightCtrl(int ledNum,int onOff) {

//        IC 灯 0；磁条卡灯 1；身份证灯 2；指纹灯 3
        if(onOff == 1){ //亮
            if(ledNum == 0)
                MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)1);// IC
            if(ledNum == 1)
                MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)1);//磁条卡灯
            if(ledNum == 2)
                MainActivity.getmSys().DLL_SysLedControl((byte) 6,(byte)1);//身份证灯
            if(ledNum == 3)
                MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)1);//指纹灯
        }else { //灭
            if(ledNum == 0)
                MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)0);// IC
            if(ledNum == 1)
                MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)0);//磁条卡灯
            if(ledNum == 2)
                MainActivity.getmSys().DLL_SysLedControl((byte) 6,(byte)0);//身份证灯
            if(ledNum == 3)
                MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)0);//指纹灯
        }
    }
    public static void lightCtrl() {
        if (light == 0) {
            light = 1;
//            MainActivity.getmSys().DLL_SysLedControl((byte) 0,(byte)1);//键盘
//            MainActivity.getmSys().DLL_SysLedControl((byte) 1,(byte)1);//指纹
//            MainActivity.getmSys().DLL_SysLedControl((byte) 2,(byte)1);//IC
//            MainActivity.getmSys().DLL_SysLedControl((byte) 3,(byte)1);//磁条卡
//            MainActivity.getmSys().DLL_SysLedControl((byte) 4,(byte)1);//蓝牙
            MainActivity.getmSys().DLL_SysLedControl((byte) 5,(byte)1);//蓝牙
            MainActivity.getmSys().DLL_SysLedControl((byte) 6,(byte)1);//身份证灯
            MainActivity.getmSys().DLL_SysLedControl((byte) 7,(byte)1);//电池充电指示灯
            MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)1);//磁条卡灯
            MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)1);//IC灯
            MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)1);//指纹灯
            MainActivity.getmSys().DLL_SysLedControl((byte) 11,(byte)1);//密码键盘灯
//            MainActivity.getmSys().DLL_SysLedControl((byte) 12,(byte)1);// 无灯
        } else {
            light = 0;
//            MainActivity.getmSys().DLL_SysLedControl((byte) 0,(byte)0);//键盘
//            MainActivity.getmSys().DLL_SysLedControl((byte) 1,(byte)0);//指纹
//            MainActivity.getmSys().DLL_SysLedControl((byte) 2,(byte)0);//IC
//            MainActivity.getmSys().DLL_SysLedControl((byte) 3,(byte)0);//磁条卡
            MainActivity.getmSys().DLL_SysLedControl((byte) 5,(byte)0);//蓝牙
            MainActivity.getmSys().DLL_SysLedControl((byte) 6,(byte)0);//身份证灯
            MainActivity.getmSys().DLL_SysLedControl((byte) 7,(byte)0);//电池充电指示灯
            MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)0);//磁条卡灯
            MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)0);// IC灯
            MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)0);//指纹灯
            MainActivity.getmSys().DLL_SysLedControl((byte) 11,(byte)0);//密码键盘灯
//            MainActivity.getmSys().DLL_SysLedControl((byte) 12,(byte)0);//无灯
        }

    }

    /**
     *
     */
//    public static void sendScreenOnOffBroadCast(){
//        Intent intent = new Intent();
//        intent.setAction("android.intent.action.SCREEN_OFF");
//        MainActivity.context.sendBroadcast(intent);
//        try {
//            Thread.sleep(10);
//            intent.setAction("android.intent.action.SCREEN_ON");
//            MainActivity.context.sendBroadcast(intent);
//
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//    }

    public static void closeSignature() {
        if (INIT_SIGN) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    int res = dmtTest.closeDMTSignDM();
                    Log.e("closeDMTSignDM", res + "");
                }
            };
            DmtThreadPool.submit(runnable);
        }
    }

    public static void clearSignature() {
        if (INIT_SIGN) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    int res = dmtTest.clearDMTSignDM();
                    Log.e("clearDMTSignDM", res + "");
                }
            };
            DmtThreadPool.submit(runnable);
        }

    }

    public static void startSignature() {
        if (INIT_SIGN) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    int res = dmtTest.startDMTSignDM();
                    Log.e("startDMTSignDM", res + "");
                }
            };
            DmtThreadPool.submit(runnable);
        }
    }

    public static void endSignature(DeviceCallback callback, boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);
                try {
                    if (INIT_SIGN) {
                        int res = dmtTest.endDMTSignDM();
                        Log.e("endDMTSignDM", res + "");
                        SystemClock.sleep(200);
                        int[] length = new int[1];
                        res = dmtTest.getcipherDMTSignDM(cipherData, length);
                        Log.e("getcipherDMTSignDM", res + "");
                        if (res == 0x90) {
                            byte[] cipher = new byte[length[0]];
                            System.arraycopy(cipherData, 0, cipher, 0, cipher.length);
                            Bundle bundle = new Bundle();
                            bundle.putByteArray("data", cipher);
                            deliverResult(callback, Result.SUCCEED, bundle, isOnMain);
                        } else {
                            Bundle bundle = new Bundle();
                            bundle.putInt("code", ErrorDefine.SIGNATURE_EN_FAIL);
                            bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.SIGNATURE_EN_FAIL));
                            deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                        }

                    } else {
                        Bundle bundle = new Bundle();
//                        bundle.putParcelableArrayList("NoPasswordTrack",(ArrayList)SignaturePad.mPoint);
                        bundle.putInt("code", ErrorDefine.SIGNATURE_INIT_FAIL);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.SIGNATURE_INIT_FAIL));
                        deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    }
                } finally {
                    deliverResult(callback, Result.COMPLETED, new Bundle(), isOnMain);
                }
            }

        };

        DmtThreadPool.submit(runnable);


    }

    public static void setSM4PrimaryKey(DeviceCallback callback, byte[] sm4key, boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);
                try {
                    if (INIT_SIGN) {
                        byte[] verify = new byte[16];
                        int res = dmtTest.setSM4PrimaryKey(sm4key, verify);
                        Log.e("setSM4PrimaryKey", res + "==");
                        if (res == DmtProtocol.STATUS_OK) {
                            Log.e("verify", ByteTool.byte2hex(verify));
                            Bundle bundle = new Bundle();
                            bundle.putString("data", ByteTool.byte2hex(verify));
                            deliverResult(callback, Result.SUCCEED, bundle, isOnMain);

                        } else {

                            Bundle bundle = new Bundle();
                            bundle.putInt("code", ErrorDefine.SIGNATURE_SM4_FAIL);
                            bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.SIGNATURE_SM4_FAIL));
                            deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                        }

                    } else {

                        Bundle bundle = new Bundle();
                        bundle.putInt("code", ErrorDefine.SIGNATURE_INIT_FAIL);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.SIGNATURE_INIT_FAIL));
                        deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    }
                } finally {
                    deliverResult(callback, Result.COMPLETED, new Bundle(), isOnMain);
                }
            }

        };

        DmtThreadPool.submit(runnable);


    }

    public static void transSM2PublicKey(DeviceCallback callback, boolean isOnMain) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);
                try {
                    if (INIT_SIGN) {

                        byte[] pubkey = new byte[64];
                        int res = dmtTest.transSM2Publickey(0, pubkey);
                        Log.e("transSM2Publickey", res + "===");
                        String pukStr = ByteTool.byte2hex(pubkey);
                        if (res == DmtProtocol.STATUS_OK) {

                            Log.e("pubkey", pukStr);
                            Bundle bundle = new Bundle();
                            bundle.putString("data", pukStr);
                            deliverResult(callback, Result.SUCCEED, bundle, isOnMain);
                        } else {

                            Bundle bundle = new Bundle();
                            bundle.putInt("code", ErrorDefine.SIGNATURE_SM2_FAIL);
                            bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.SIGNATURE_SM2_FAIL));
                            deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                        }
                    } else {

                        Bundle bundle = new Bundle();
                        bundle.putInt("code", ErrorDefine.SIGNATURE_INIT_FAIL);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.SIGNATURE_INIT_FAIL));
                        deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    }
                } finally {
                    deliverResult(callback, Result.COMPLETED, new Bundle(), isOnMain);
                }

            }

        };

        DmtThreadPool.submit(runnable);

    }

    public static void initSignPad() {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                int res = dmtTest.connectDMTSignDM();
                Log.e("initSignPad", "connectDMTSignDM--" + res);
                if (res != DmtProtocol.STATUS_OK) {
                    Log.e("connectDMTSignDM", "fail");
                    return;
                }
                StringBuffer DevVer = new StringBuffer();
                res = dmtTest.getversionDMTSignDM(DevVer);
                if (res == DmtProtocol.STATUS_OK) {

                    Log.e("getVer", "Ver:" + DevVer);
                    INIT_SIGN = true;

                } else {
                    INIT_SIGN = false;
                }
            }
        };

        DmtThreadPool.submit(runnable);

    }

    public static void setKeyValue(String key, String value) {
        Context ctx = MainActivity.context;
        SharedPreferences sp = ctx.getSharedPreferences(ConstDefine.SP_FILE_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, value);
        editor.commit();
    }

    public static String getValue(String key) {
        Context ctx = MainActivity.context;
        SharedPreferences sp = ctx.getSharedPreferences(ConstDefine.SP_FILE_NAME, MODE_PRIVATE);

        return sp.getString(key, "");
    }

    public static void setSerialCode(String code){
        code = code.trim();
        MainActivity.getmSys().DLL_SysWriteMtkSN((byte) code.length(),code.getBytes());
        LogUtil.e(TAG,"写入序列号是：" + code);
    }
    public static String getSerialCode(){
        byte[] b = new byte[64];
        int ret = MainActivity.getmSys().DLL_SysReadMtkSN(b);
        String codeStr = new String(b).trim();
        LogUtil.e(TAG,"ret =" + ret + "--读出的序列号是：" + codeStr);
        return codeStr;
    }

    //修改蓝牙名称
    public static void changeBlueName(String name){
        Context ctx = MainActivity.context;
        SharedPreferences sp = ctx.getSharedPreferences(ConstDefine.SP_FILE_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(ConstDefine.SP_KEY_BLUE_NAME, name);
        editor.commit();
    }

    public static void allOpen() {

        initFinancial();
        initFingerModule();
        initKeyBoard();

    }

    public static boolean initFinancial() {

        financialModule.PowerOn();
        return financialModule.init();
    }

    public static void allInit(DeviceCallback callback) {
        Log.e("device", "init");
        Thread initThread = new Thread() {
            @Override
            public void run() {
                try {
                    boolean key;
                    final boolean[] finger = new boolean[1];
                    boolean finan;
                    key = initKeyBoard();
                    Bundle bundle1 = new Bundle();

                    if (key) {
                        SystemClock.sleep(300);
                        byte[] version = new byte[32];
                        int[] len = new int[1];
                        int res = keyBoardModule.getVersion(version, len);
                        byte[] buf = new byte[len[0]];
                        System.arraycopy(version, 0, buf, 0, len[0]);
                        Log.e("version", new String(buf));
                        if (res == 0) {
                            key = true;

                        }
                    }
                    if (!key) {
                        bundle1.putBoolean("keyBoard", false);
                        deliverResult(callback, Result.ERROR, bundle1, true);
                    } else {
                        bundle1.putBoolean("keyBoard", true);
                    }

                    SystemClock.sleep(500);
                    financialModule.PowerOff();
                    finan = initFinancial();
                    if (!finan) {

                        bundle1.putBoolean("finan", false);
                        deliverResult(callback, Result.ERROR, bundle1, true);
                    } else {
                        boolean breakflag = false;
                        for (int i = 0; i < 2; i++) {
                            int res = -1;
                            Timer tm = new Timer(10000);
                            tm.start();
                            while (true) {
                                if (tm.timeOut()) {
                                    Log.e(TAG, "open  timeOut!!");
                                    financialModule.PowerOff();
                                    financialModule.init();
                                    if (i == 1) {
                                        bundle1.putBoolean("finan", false);
                                        deliverResult(callback, Result.ERROR, bundle1, true);
                                    }
                                    break;
                                }
                                byte[] bootVer = new byte[3];
                                byte[] appVer = new byte[3];
                                res = financialModule.readVersion(bootVer, appVer);
                                Log.e(TAG, "test res:" + res);
                                if (res == 0) {
                                    if (financialModule.EmvLib_Init() == 0) {
                                        Log.e("EmvLib_Init", "ok");
                                    }
                                    bundle1.putBoolean("finan", true);
                                    breakflag = true;
                                    break;
                                }
                                financialModule.flush();
                                SystemClock.sleep(10);
                            }
                            if (breakflag) {
                                break;
                            }
                        }
                    }
                    /**
                     * 检测指纹
                     */

                    if (ConstDefine.getFingerprintPort() != null) {

                        finger[0] = initFingerModule();
                        if (finger[0]) {
                            SystemClock.sleep(1200);
                            byte[] version = new byte[32];
                            int[] len = new int[1];
                            int res = tesoFingerPrintModule.readVersion(version, len);
                            if (res == 0) {
                                finger[0] = true;
                            }
                        }
                        if (!finger[0]) {
                            bundle1.putBoolean("finger", false);
                            deliverResult(callback, Result.ERROR, bundle1, true);
                        }
                        Log.e("here", "=----" + key + finger[0] + finan);
                        if (key && finger[0] && finan) {
                            deliverResult(callback, Result.SUCCEED, new Bundle(), true);
                        }
                        tesoFingerPrintModule.PowerOff();
                        return;

                    }

                    boolean finalKey = key;


                    mUsbUtil = USBComm.getInstance(MainActivity.context);

                    mUsbUtil.setConnectListener(new OnConnectListener() {

                        @Override
                        public void onConnected(int type, TcFingerClient client, USBComm usbComm) {

                            Log.e("fingerInit", "connected" + type);
                            finger[0] = true;

                            if (finalKey && finger[0] && finan) {

                                deliverResult(callback, Result.SUCCEED, new Bundle(), true);

                            }
                            if (type == 1) {
                                mClient = client;


                                mUsbUtil.disconnectDevice();
                                tesoFingerPrintModule.PowerOff();
                            }

                            if (type == 2) {


                                usbComm.closeDev();
                                tesoFingerPrintModule.PowerOff();
                            }
                            if (type == 3) {

                                mUsbUtil.disconnectDevice();
                                tesoFingerPrintModule.PowerOff();

                            }


                        }

                        @Override
                        public void onConnectFailed(int code, String msg) {

                            bundle1.putBoolean("finger", false);
                            Log.e("fingerInit", msg);

                            deliverResult(callback, Result.ERROR, bundle1, true);

                            mUsbUtil.disconnectDevice();

                            mUsbUtil.closeDev();

                            tesoFingerPrintModule.PowerOff();


                        }
                    });
                    SystemClock.sleep(500);

                    initUsbFingerModule();
                } finally {

                    deliverResult(callback, Result.COMPLETED, new Bundle(), true);
                }
            }

        };
        initThread.start();
    }




    /**********************************
     * soft sm2
     **************************************
     * @param deviceCallback*/
    public static SM2keyPair getSM2keypair(DeviceCallback deviceCallback) {
        SM2keyPair keypair = SMUtil.generatorSm2KeyPair();
        Bundle bundle = new Bundle();
        bundle.putString("data",keypair.pukX + keypair.pukY);
        deviceCallback.onSuccess(bundle);
        LogUtil.e(TAG,"private key =" + keypair.prvk + "\n X==" + keypair.pukX + "\n Y==" + keypair.pukY);
        return keypair;
    }

    public static byte[] SM2Decipher(String prvk, String content, int mode) {
        if (prvk.length() > 0) {
            byte[] buf = SMUtil.SM2PrvDecrypt(prvk, content, mode);
            return buf;
        }
        return null;

    }
    /*************************************************************************/
    /**
     * 获取唯一标识
     *
     * @param
     * @return
     */
    public static String getDeviceId() {

//        String btAddress = BlueServer.getBTAddress();
        String btAddress = getValue(ConstDefine.SP_KEY_BLUE_Device_ID);
//        String mac = MacUtils.getMac();
//        return getMacFromDevice();
        btAddress = "ZG" + btAddress.replace(":","");
        return btAddress;
    }

    public static String getDeviceVersion(){
        PackageManager manager = MainActivity.context.getPackageManager();
        String name = null;
//        Build.DISPLAY
//        try {
//            PackageInfo info = manager.getPackageInfo(MainActivity.context.getPackageName(), 0);
            name = Build.DEVICE;
//            Log.e("GJ","\nBuild.BOARD："+Build.BOARD+"\nBuild.BRAND："+Build.BRAND+"\nBuild.DEVICE："+Build.DEVICE+"\nBuild.DISPLAY："+Build.DISPLAY
//            +"\nBuild.FINGERPRINT："+Build.FINGERPRINT+"\nBuild.SERIAL："+Build.SERIAL+"\nBuild.MANUFACTURER："+Build.MANUFACTURER+"\nBuild.MODEL："+Build.MODEL
//            +"\nBuild.HARDWARE："+Build.HARDWARE+"\nBuild.PRODUCT："+Build.PRODUCT+"\nBuild.VERSION.INCREMENTAL："+Build.VERSION.INCREMENTAL
//            +"\nBuild.VERSION.RELEASE："+Build.VERSION.RELEASE+"\nBuild.VERSION.SDK_INT："+Build.VERSION.SDK_INT+"\nBuild.USER："+Build.USER);

//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }

        return name;
    }
    /**
     * USB指纹模块
     */


    public static boolean initUsbFingerModule() {

        tesoFingerPrintModule.PowerOn();
        SystemClock.sleep(300);
        Log.e("initUsbFingerModule", "===");
        // 设置设备使用协议
        mUsbUtil.setProtocol(USBUtil.Protocol.SIMPLE);
        // 设置特征类型
        FpConfig.setFeatureType(FpConfig.FEATURE_TYPE_OLDBASE64);
        // 设置出图规格
        FpConfig.setImageType(FpConfig.IMAGE_BIG);

        mUsbUtil.connectDevice();

        return true;
    }


    /**********************************
     * 指纹模块
     ***************************************/

    public static boolean initFingerModule() {
        tesoFingerPrintModule.PowerOn();
        return tesoFingerPrintModule.init();
    }

    public static void closeFingerModule() {


        if (ConstDefine.getFingerprintPort() != null) {
            tesoFingerPrintModule.closeSerialPort();
        } else {
            if (mUsbUtil != null)
                mUsbUtil.disconnectDevice();
        }
        tesoFingerPrintModule.PowerOff();
        tesoFingerPrintModule.lightOff();
    }

    private static FingerDevice mFingerDevice = null;
    private static zzFingerAlg mZzFingerAlg = null;

    public static void getFingerFeature(final DeviceCallback callback, int timeOutMs, final boolean isOnMain) {

        mFingerDevice = new FingerDevice();
        deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);
        MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)1);
        byte[] ver = new byte[30];
        byte[] errMsg = new byte[200];
        int ret = -1;
        try {
            ret = mFingerDevice.GetDevVersion(mPortPath,115200,ver.length,ver,errMsg);
            LogUtil.e(TAG,"ret == " + ret + "----ver == " + new String(ver).trim() + "----" + new String(errMsg).trim());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(ret == 0){ //中正模块
            int nResult = 0;
            byte[] m_B64_bFeature = new byte[344];
            try {
                nResult = mFingerDevice.GetFeature(mPortPath, 115200, timeOutMs, m_B64_bFeature, errMsg);
                LogUtil.e(TAG, " nResult == " + nResult);
                if (nResult != 0) { //读取错误

                    Bundle bundle = new Bundle();
                    bundle.putInt("code", nResult);
                    bundle.putString("message", new String(errMsg, "GBK").trim());
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                } else {
                    String feat_b64 = new String(m_B64_bFeature).trim();
                    Bundle bundle = new Bundle();
                    bundle.putString("data", feat_b64);
                    deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                }
                MainActivity.getmSys().DLL_SysLedControl((byte) 10, (byte) 0);

            } catch (Exception e) {
                e.printStackTrace();
            }


        }else { //天诚指纹
            InitFinger();
            mTcFingerClientApi.DLL_tcGetFeature(timeOutMs, new com.techshino.fp.client.Callback() {

                @Override
                public void onSuccess(com.techshino.fp.entity.FingerResult result) {
                    byte[] template = result.getTemplate();

//				byte[] gbBytes = FpImage.tcFeaToGB(template);
//
//				byte[] feaBytes = FpImage.gbToTcFea(gbBytes);

                    mTemplate = template;
                    String feaStr = Base64.encodeToString(template, Base64.NO_WRAP);
                    Bundle bundle = new Bundle();
                    bundle.putString("data", feaStr);
                    deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
//                tesoFingerPrintModule.lightOff();
                    MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)0);
                    mTcFingerClientApi.clear();
                    mTcFingerClientApi.DLL_FingerRelease();
                }

                @Override
                public void onError(int errorCode) {
                    mTcFingerClientApi.clear();
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.FINGERPRINT_FREATURE_TIMEOUT);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.FINGERPRINT_FREATURE_TIMEOUT));
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                    MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)0);
                }
            });
        }


    }

    public static String getSDCardPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();  //获取跟目录
            return sdDir.toString();
        } else {
            return null;
        }
    }

    public static void fingerCancel(){
        mTcFingerClientApi.DLL_tcCancel();
        mTcFingerClientApi.DLL_FingerRelease();
        MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)0);
    }

    public static String getFingerVersion(){
        InitFinger();
        com.techshino.fp.entity.FingerResult fingerResult = mTcFingerClientApi.DLL_tcGetDevSn();
        return fingerResult.getResult();
    }


    public static int getFingerPic(final DeviceCallback callback, int timeOutMs, final boolean isOnMain) {
        MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)1);
        InitFinger();
        deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);
        mTcFingerClientApi.DLL_tcSetBaudRate(7);
        mBaudrate = 115200;
//		mTcFingerClient = mSerialPortUtil.openDevice(mPortPath, mBaudrate);
        mTcFingerClientApi.DLL_OpenDevice(mPortPath, mBaudrate);

        mTcFingerClientApi.DLL_tcGetImage(timeOutMs, new com.techshino.fp.client.Callback() {
            @Override
            public void onSuccess(com.techshino.fp.entity.FingerResult result) {

                Bitmap bitmap = BitmapFactory.decodeByteArray(
                        result.getImgBytes(), 0, result.getImgBytes().length);
//                Bitmap bitmap2 = FpCoder.getRedTransparentBitmap(bitmap);
                Bitmap bitmap2 = FpCoder.getTransparentBitmap(bitmap, Color.RED);
//                mImageView.setImageBitmap(bitmap2);
//                fingerImage = bitmap;
                LogUtil.e(TAG,"获取的指纹图片大小getByteCount：" + bitmap2.getByteCount());
                Bundle bundle = new Bundle();
//                System.arraycopy(data,28,buff,0,len[0]-28);
                bundle.putString("data", "");
                bundle.putInt("zip",1);
                byte[] bytes = Bitmap2Bytes(bitmap2);
                bundle.putByteArray("imgBuff",bytes);
                LogUtil.e(TAG,"获取的指纹图片字节数：" + bytes.length);
                deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
//                tesoFingerPrintModule.lightOff();
                mTcFingerClientApi.DLL_FingerRelease(); //关闭指纹
                MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)0);
                reConnect(9600);
            }
            @Override
            public void onError(int errorCode) {
                Bundle bundle = new Bundle();
                bundle.putInt("code", ErrorDefine.FINGERPRINT_FREATURE_TIMEOUT);
                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.FINGERPRINT_FREATURE_TIMEOUT));
                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                MainActivity.getmSys().DLL_SysLedControl((byte) 10,(byte)0);
                reConnect(9600);
            }
        });
            return 0;
    }
    public static byte[] Bitmap2Bytes(Bitmap bm) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }
    private static void reConnect(int baudRate) {
        mTcFingerClientApi.DLL_tcSetBaudRate(3);
        mBaudrate = baudRate;
        mTcFingerClientApi.DLL_OpenDevice(mPortPath, mBaudrate);
    }

    public static int Encode0x30(byte[] chDst, byte[] pSrc, int nLen) {
//        byte[] chDst = pDst;
        byte[] bySrc = pSrc;

        /* 若返回指针为NULL，则为求取存储所需的字节长度(含'\0') */
        if (nLen < 0)
            return (-3);
        if (chDst == null) {
            return -(2 * nLen + 1);
        }
        if (pSrc == null) {
            return (-3);
        }

        /* 一个字节折成两个低4位或上0x30的可见字符(高在前) */
        for (int i = 0; i < nLen; i++) {
            chDst[i * 2] = (byte) (0x30 | (((bySrc[i]) >> 4) & 0x0F));
            chDst[i * 2 + 1] = (byte) (0x30 | ((bySrc[i]) & 0x0F));
        }

        chDst[nLen * 2] = '\0';
        return 0;
    }

    public static int fingerMatch(byte[] feature,byte[] templet,final DeviceCallback callback, int timeOutMs, final boolean isOnMain){
        if (callback == null)
            return ErrorDefine.NO_CALLBACK;
        if (ConstDefine.getFingerprintPort() == null) {
            tesoFingerPrintModule.PowerOn();

            mUsbUtil = USBComm.getInstance(MainActivity.context);

            mUsbUtil.setConnectListener(new OnConnectListener() {

                @Override
                public void onConnected(int type, TcFingerClient client, USBComm usbComm) {

                    if (type == 1) {
                        mClient = client;
                        if (mClient == null) {
                            Bundle bundle = new Bundle();
                            bundle.putInt("code", ErrorDefine.FINGERPRINT_FREATURE_ERR);
                            bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.FINGERPRINT_FREATURE_ERR));
                            deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                            return;
                        }
                        FingerResult result =  mClient.tcMatch(feature,templet);

                        Log.e("result",result.getStatus()+"==");

                       if(result.getStatus()>=0){

                           Bundle bundle = new Bundle();
                           bundle.putInt("type", 1);
                           deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                           tesoFingerPrintModule.lightOff();

                           deliverResult(callback, DeviceInterface.Result.COMPLETED, new Bundle(), isOnMain);
                           tesoFingerPrintModule.PowerOff();
                           mUsbUtil.disconnectDevice();
                       }else{

                           Bundle bundle = new Bundle();
                           bundle.putInt("code", ErrorDefine.FINGERPRINT_MATCH_ERR);
                           bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.FINGERPRINT_MATCH_ERR));
                           deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                           tesoFingerPrintModule.lightOff();
                           tesoFingerPrintModule.PowerOff();
                           mUsbUtil.disconnectDevice();
                           deliverResult(callback, DeviceInterface.Result.COMPLETED, new Bundle(), isOnMain);
                       }


                    }else{

                        Bundle bundle = new Bundle();
                        bundle.putInt("code", ErrorDefine.FINGERPRINT_NO_HAVE);
                        bundle.putString("message", "Finger Unsupported");
                        deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);

                    }



                }

                @Override
                public void onConnectFailed(int code, String msg) {

                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.FINGERPRINT_RESPOND_ERR);
                    bundle.putString("message", "Finger error");
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);


                }
            });
            deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);
            SystemClock.sleep(500);
            mUsbUtil.connectDevice();
            tesoFingerPrintModule.lightOn();


            return 0;
        } else {

            if (callback == null) {

                return ErrorDefine.NO_CALLBACK;
            }
            if (fingerPrintRunnable != null) {
                fingerPrintRunnable.stopRun();
                fingerPrintRunnable = null;
            }
            fingerPrintRunnable = new FingerPrintRunnable(FingerPrintRunnable.Action.GET_PIC, callback, timeOutMs, isOnMain);
            fingerThreadPool.execute(fingerPrintRunnable);
            return 0;
        }

    }


    public static int getTemplet(final DeviceCallback callback, int timeOutMs, final boolean isOnMain){
        if (callback == null)
            return ErrorDefine.NO_CALLBACK;
        if (ConstDefine.getFingerprintPort() == null) {
            tesoFingerPrintModule.PowerOn();

            mUsbUtil = USBComm.getInstance(MainActivity.context);

            mUsbUtil.setConnectListener(new OnConnectListener() {

                @Override
                public void onConnected(int type, TcFingerClient client, USBComm usbComm) {

                    if (type == 1) {
                        mClient = client;
                        if (mClient == null) {
                            Bundle bundle = new Bundle();
                            bundle.putInt("code", ErrorDefine.FINGERPRINT_FREATURE_ERR);
                            bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.FINGERPRINT_FREATURE_ERR));
                            deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                            return;
                        }
                        mClient.tcEnroll(new Callback() {
                            @Override
                            public void onSuccess(FingerResult result) {


                                byte[] feature = result.getTemplate();
                                Log.e("feature",new String(feature)+"!!!");
                                Bundle bundle = new Bundle();
                                bundle.putInt("type", 1);
                                bundle.putString("data", new String(feature).trim());
                                deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
                                tesoFingerPrintModule.lightOff();
                                deliverResult(callback, DeviceInterface.Result.COMPLETED, new Bundle(), isOnMain);
                                tesoFingerPrintModule.PowerOff();
                                mUsbUtil.disconnectDevice();

                            }
                            @Override
                            public void onProcess(int code, byte[] img) {
                                Log.e("onProcess",code+"---");
                                super.onProcess(code, img);
                                switch (code) {
                                    case FpConst.TCY_CAPTUREIMAGE:
//                                        MainActivity.startFingerPrint();
                                        break;
                                    case FpConst.TCY_GETIMAGE:
                                        MainActivity.stopFingerPrint();
                                        break;
                                    case FpConst.TCY_TOLV:
//
                                        break;
                                    default:
                                        break;
                                }
                            }
                            @Override
                            public void onError(int errorCode) {
                                Log.e("onError",errorCode+"!!!");
                                Bundle bundle = new Bundle();
                                bundle.putInt("code", ErrorDefine.FINGERPRINT_ENROLL);
                                bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.FINGERPRINT_ENROLL));
                                deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
                                return;


                            }
                        },timeOutMs);




                    }else{

                        Bundle bundle = new Bundle();
                        bundle.putInt("code", ErrorDefine.FINGERPRINT_NO_HAVE);
                        bundle.putString("message", "Finger Unsupported");
                        deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);

                    }



                }

                @Override
                public void onConnectFailed(int code, String msg) {

                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.FINGERPRINT_RESPOND_ERR);
                    bundle.putString("message", "Finger error");
                    deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);


                }
            });
            deliverResult(callback, DeviceInterface.Result.START, null, isOnMain);
            SystemClock.sleep(500);
            mUsbUtil.connectDevice();
            tesoFingerPrintModule.lightOn();


            return 0;
        } else {

            if (callback == null) {

                return ErrorDefine.NO_CALLBACK;
            }
            if (fingerPrintRunnable != null) {
                fingerPrintRunnable.stopRun();
                fingerPrintRunnable = null;
            }
            fingerPrintRunnable = new FingerPrintRunnable(FingerPrintRunnable.Action.GET_PIC, callback, timeOutMs, isOnMain);
            fingerThreadPool.execute(fingerPrintRunnable);
            return 0;
        }

    }


    public static int getFingerVer(final DeviceCallback callback, int timeOutMs, final boolean isOnMain) {

        String version = getFingerVersion();
        Bundle bundle = new Bundle();
        if(TextUtils.isEmpty(version)){
            bundle.putInt("code", ErrorDefine.FINGERPRINT_RESPOND_ERR);
            bundle.putString("message", "Finger error");
            deliverResult(callback, DeviceInterface.Result.ERROR, bundle, isOnMain);
        }else {
            bundle.putString("data", version);
            deliverResult(callback, DeviceInterface.Result.SUCCEED, bundle, isOnMain);
        }

            return 0;

    }

    public static void cancelFingerPrint() {
        SystemClock.sleep(1500);
        if (USBComm.TYPE == 3) {
            Log.e("well", "cancelFingerPrint");
            try {
                FpDriverV22.FPICancel();
            } catch (Throwable ex) {
                ex.printStackTrace();
            }
        }

        if (mClient != null) {

            mClient.tcCancel();
            return;
        }
        if (fingerPrintRunnable != null) {
            fingerPrintRunnable.stopRun();
            fingerPrintRunnable = null;
        }
    }


    /*******************************密码键盘******************************************/








    public static int calcMAC(int macMode, int mainKey, int workIndex, byte[] data, final DeviceCallback callback, final boolean isOnMain) {
        if (callback == null)
            return ErrorDefine.NO_CALLBACK;
        Log.e("calcMAC", "calcMAC");
        Runnable r = new Runnable() {
            @Override
            public void run() {
                if (macMode == 0x01) {
                    //x99
                    keyBoardModule.setEncryptMode("06", "03");
                }
                if (macMode == 0x02) {
                    //x9.19
                    keyBoardModule.setEncryptMode("06", "01");
                }
                deliverResult(callback, Result.START, null, isOnMain);

                String index = String.format("%02d", Integer.valueOf(mainKey));
                String windex = String.format("%02d", Integer.valueOf(workIndex));
                keyBoardModule.setEncryptKey(index, windex);//mac密钥用的0x03的工作密钥
                byte[] buff = new byte[2048];
                int[] len = new int[1];
                byte[] rebuff;
                if (data.length <= 256) {
                    int res = keyBoardModule.getMac(ByteTool.byte2hex(data), buff, len);
                    if(res!=0){
                        Bundle bundle = new Bundle();
                        bundle.putInt("code", ErrorDefine.CALC_MAC_ERROR);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.CALC_MAC_ERROR));
                        deliverResult(callback, Result.ERROR, bundle, isOnMain);

                    }else {
                        Log.e("buff", ByteTool.byte2hex(buff, 0, len[0], false));
                        rebuff = new byte[len[0]];
                        System.arraycopy(buff, 0, rebuff, 0, rebuff.length);
                        Bundle bundle = new Bundle();
                        bundle.putByteArray("data",rebuff);
                        deliverResult(callback, Result.SUCCEED, bundle, isOnMain);

                    }
                } else {
                    int res = keyBoardModule.getMacBD(data, buff, len);
                    Log.e("BDbuff", ByteTool.byte2hex(buff, 0, len[0], false));
                    if(res!=0){
                        Bundle bundle = new Bundle();
                        bundle.putInt("code", ErrorDefine.CALC_MAC_ERROR);
                        bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.CALC_MAC_ERROR));
                        deliverResult(callback, Result.ERROR, bundle, isOnMain);

                    }else {
                        Log.e("buff", ByteTool.byte2hex(buff, 0, len[0], false));
                        rebuff = new byte[len[0]];
                        System.arraycopy(buff, 0, rebuff, 0, rebuff.length);
                        Bundle bundle = new Bundle();
                        bundle.putByteArray("data",rebuff);
                        deliverResult(callback, Result.SUCCEED, bundle, isOnMain);

                    }

                }

                Log.e("calcMAC", "mac校验");


                deliverResult(callback, Result.COMPLETED, new Bundle(), isOnMain);
            }
        };
        keyThreadPool.execute(r);
        return 0;
    }




    /**
     * 取消输入
     */
    public static void cancelKeyBoardInput() {


        if (keyBoardRunnable != null && keyBoardRunnable.isInputting()) {
            keyBoardRunnable.stopRun();
            keyBoardRunnable = null;
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    LogUtil.e(TAG,"关闭了密码键盘------------");
                    MainActivity.getmMainPci().DLL_PciKbClose(); //关闭键盘

//                    keyBoardModule.cancelInput();
//                    keyBoardModule.flush();
                }
            };
            keyThreadPool.submit(r);
        } else if (keyBoardRunnable != null) {
            keyBoardRunnable.stopRun();
//            keyBoardModule.flush();
            keyBoardRunnable = null;

        }
    }




    public static void keySetEncryptMode(int encrypt, String endType, String activeMkey, String activeWkey, final DeviceCallback callback, final boolean isOnMain) {
        if (keyBoardRunnable != null) {
            keyBoardRunnable.stopRun();
        }
        Log.e("encrypt:", "==" + encrypt);
        Runnable r = new Runnable() {
            @Override
            public void run() {

//                if (keyBoardRunnable != null && keyBoardRunnable.getAlreadyInputlength() > 0) {
//
//                    keyBoardModule.cancelInput();
//                    keyBoardModule.flush();
//                }
                int res = 0;
                if (encrypt == KEY_SM) {
//                    res = setKeyEncryptMode(SM4_MODE);
                    isEncrypted = KEY_SM;
                    Log.e("sm4res:", res + "---");
                } else if (encrypt == KEY_3DES) {
//                    res = setKeyEncryptMode(THREE_DES_MODE);
                    isEncrypted = KEY_3DES;
                    Log.e("3desres:", res + "---");
                } else if (encrypt == KEY_NOENCRYPTION) {
//                    res = setKeyEncryptMode(NO_ENCRYPTION);
                    isEncrypted = KEY_NOENCRYPTION;
                    Log.e("noencry:", res + "---");
                }
                if (endType != null) {
//                    res = keyBoardModule.setEncryptMode("05", endType);

                    Log.e("setEncryptMode", res + "---" + endType);
                }

                if (activeMkey != null && activeWkey != null) {
//                    res = keyBoardModule.setEncryptKey(activeMkey, activeWkey);

                    Log.e("setEncryptKey", res + "---");
                }


                if (res == 0) {
                    Bundle bundle = new Bundle();
                    bundle.putString("data", res + "");
                    deliverResult(callback, Result.SUCCEED, bundle, isOnMain);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putInt("code", ErrorDefine.INPUT_MAINKEY_ERR);
                    bundle.putString("message", ErrorDefine.getErrorDescribe(ErrorDefine.INPUT_MAINKEY_ERR));
                    deliverResult(callback, Result.ERROR, bundle, isOnMain);

                }
            }
        };
        keyThreadPool.submit(r);

    }


    public static void closeKeyBoard() {

        keyBoardModule.PowerOffKeyBoard();
    }

    public static boolean initKeyBoard() {
        keyBoardModule.PowerOnKeyBoard();
        return keyBoardModule.isOpen();

    }


    /***********************************密码键盘结束**************************************/


    /********************************金融板*****************************************/
    public static int testPsamSlot(final byte slot) {
        byte[] ATD = new byte[100];
        int ret = -1;
        try {
            ret = financialModule.libIccOpen(slot, (byte) 0x01, ATD);
            if (ret != 0) {
                Log.e("Icc_Open", ret + "!!");
                return ret;
            } else {
                return ret;
            }
//            byte sendData[] = new byte[530];
//            byte cmd[] = new byte[4];
//            cmd[0] = 0x00; // 0-3 cmd
//            cmd[1] = (byte) 0xa4;
//            cmd[2] = 0x04;
//            cmd[3] = 0x00;
//            short Lc = 0x0e;
//            short Le = 256;
//            byte[] dataIn = new byte[512];
//            // 02 B7 07 00 14 00 00 A4 04 00 00 0E 31 50 41 59 2E 53 59 53 2E 44 44
//            // 46 30 B4 82
//            String sendmsg = "1PAY.SYS.DDF01";
//            sendData = sendmsg.getBytes();
//            System.arraycopy(sendData, 0, dataIn, 0, sendData.length);
//            APDU_SEND ApduSend = new APDU_SEND(cmd, Lc, dataIn, Le);
//            APDU_RESP ApduResp = new APDU_RESP();
//            ret = financialModule.Icc_Command(slot, ApduSend, ApduResp);
//            Log.e("testPsamSlot[ run ]", "Command ret = " + ret);
        } finally {
            financialModule.libIccClose(slot);
        }


    }

    /**
     * 升级金融板固件
     *
     * @param fileName
     * @param callback
     * @param isOnMain
     */
    public static void updateFw(String fileName, final DeviceCallback callback, boolean isOnMain) {
        FwUpdateModule module = new FwUpdateModule();
        try {
            module.readFile(fileName);
            module.beginDownLoad(callback);
            Thread.sleep(1000);
            module.mcuReset();

        } catch (IOException e) {

            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        module.setCallback(callback, isOnMain);
//        module.startDownload();
    }



    /**
     * ARPC校验
     *
     * @param ICType
     * @param ARPC
     * @param ScriptStr
     * @param
     * @return
     */
    public static int ARPCExecuteScript(int ICType, String ARPC, String ScriptStr, final DeviceCallback callback, final int timeOutMs, final boolean isOnMain) {
        if (callback == null)
            return ErrorDefine.NO_CALLBACK;
        if (financialRunnable != null) {
            financialRunnable.stopRun();
            financialRunnable = null;
        }
        financialRunnable = new FinancialRunnable(ICType, ARPC, ScriptStr, callback, timeOutMs, isOnMain);
        finanThreadPool.execute(financialRunnable);
        return 0;

    }

    /**
     * 自动模式读取明细
     *
     * @param callback
     * @param timeOutMs
     * @return
     */
    public static int readLoadLog(final DeviceCallback callback, EmvOptions options, final int timeOutMs, final boolean isOnMain) {
        if (callback == null)
            return ErrorDefine.NO_CALLBACK;
        if (financialRunnable != null) {
            financialRunnable.stopRun();
            financialRunnable = null;
        }
        financialRunnable = new FinancialRunnable(FinancialRunnable.Action.AUTO_READ_LOAD, options, callback, timeOutMs, isOnMain);
        finanThreadPool.execute(financialRunnable);
        return 0;
    }

    /**
     * 自动模式读取交易记录
     *
     * @param callback
     * @param timeOutMs
     * @return
     */
    public static int autoReadLog(final DeviceCallback callback, EmvOptions options, final int timeOutMs, final boolean isOnMain) {
        if (callback == null)
            return ErrorDefine.NO_CALLBACK;
        if (financialRunnable != null) {
            financialRunnable.stopRun();
            financialRunnable = null;
        }
        financialRunnable = new FinancialRunnable(FinancialRunnable.Action.AUTO_READ_LOG, options, callback, timeOutMs, isOnMain);
        finanThreadPool.execute(financialRunnable);
        return 0;
    }

    /**
     * 非接模式读取明细
     *
     * @param callback
     * @param timeOutMs
     * @return
     */
    public static int readPicLoadLog(final DeviceCallback callback, EmvOptions options, final int timeOutMs, final boolean isOnMain) {
        if (callback == null)
            return ErrorDefine.NO_CALLBACK;
        if (financialRunnable != null) {
            financialRunnable.stopRun();
            financialRunnable = null;
        }
        financialRunnable = new FinancialRunnable(FinancialRunnable.Action.READ_PIC_LOAD, options, callback, timeOutMs, isOnMain);
        finanThreadPool.execute(financialRunnable);
        return 0;
    }

    /**
     * 接触读取交易明细
     *
     * @param callback
     * @param timeOutMs
     * @return
     */
    public static int readIcLoadLog(final DeviceCallback callback, EmvOptions options, final int timeOutMs, final boolean isOnMain) {
        if (callback == null)
            return ErrorDefine.NO_CALLBACK;
        if (financialRunnable != null) {
            financialRunnable.stopRun();
            financialRunnable = null;
        }
        financialRunnable = new FinancialRunnable(FinancialRunnable.Action.READ_IC_LOAD, options, callback, timeOutMs, isOnMain);
        finanThreadPool.execute(financialRunnable);
        return 0;
    }

    /**
     * 非接模式读取明细
     *
     * @param callback
     * @param timeOutMs
     * @return
     */
    public static int readPicLog(final DeviceCallback callback, EmvOptions options, final int timeOutMs, final boolean isOnMain) {
        if (callback == null)
            return ErrorDefine.NO_CALLBACK;
        if (financialRunnable != null) {
            financialRunnable.stopRun();
            financialRunnable = null;
        }
        financialRunnable = new FinancialRunnable(FinancialRunnable.Action.READ_PIC_LOG, options, callback, timeOutMs, isOnMain);
        finanThreadPool.execute(financialRunnable);
        return 0;
    }

    /**
     * 接触读取交易明细
     *
     * @param callback
     * @param timeOutMs
     * @return
     */
    public static int readIcLog(final DeviceCallback callback, EmvOptions options, final int timeOutMs, final boolean isOnMain) {
        if (callback == null)
            return ErrorDefine.NO_CALLBACK;
        callback.onStart();
        byte[] log = new byte[1024];
        int len[] = new int[1];
        int ret = SiecomDevice.SyncGetLog(0,log,len);
        Bundle bundle = new Bundle();
        if(ret == 0){
            List<TradeLogBean> list = com.siecom.tools.ByteTool.parseLog(log);
            bundle.putParcelableArrayList("data", (ArrayList<TradeLogBean>) list);
            callback.onSuccess(bundle);
        }else {
            bundle.putInt("code",-1);
            bundle.putString("message","read log error");
            callback.onError(bundle);
        }

        callback.onCompleted(new Bundle());
        return 0;
    }

    /**
     * 非接读取标签
     *
     * @param callback
     * @param
     * @return
     */
    public static int readPiccInfo(final DeviceCallback callback, EmvOptions options,
                                   final String[] wantTags,
                                   com.siecom.proto.Message.siecomproto msg,
                                   final boolean isOnMain) {
        String tagList = "";
        //解析传进来的标签
        try {
            JSONObject jsonObject = new JSONObject(msg.getRequest());
            if(jsonObject.has("tagList")){
               tagList = jsonObject.getString("tagList");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        String finalTagList = tagList;
        SiecomDevice.ReadBankCard(1, null, new SiecomTask.TaskCallback() {
            @Override
            public void onStart(Bundle bundle) {
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.startInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)1);
                        MainActivity.startNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.startSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.startInoneCard();
                        break;

                }
            }

            @Override
            public void onSucceed(Bundle bundle) {
                BankCardInfoBean data = bundle.getParcelable("data");
                LogUtil.e(TAG,"onSucceed data == " + data.toString());
                com.siecom.bean.BankCardInfoBean bean = new com.siecom.bean.BankCardInfoBean();
                bean.cardNo = data.cardNo;
                bean.cardType = 2;
                bean.setICChipData(data.ICChipData);
                parseAndSetCardInfo(finalTagList,bean);
                Bundle bund = new Bundle();
                bund.putParcelable("data",bean);
                callback.onSuccess(bund);
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.stopInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)0);
                        MainActivity.stopNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.stopSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.stopInoneCard();
                        break;

                }
            }

            @Override
            public void onError(Bundle bundle) {
                MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)0);
                LogUtil.e(TAG,"onError data == " + bundle.getInt("code"));
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.stopInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.stopNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.stopSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.stopInoneCard();
                        break;

                }
                callback.onError(bundle);

            }
        },msg.getTimeout());
        return 0;
    }

    /**
     * @param callback
     * @param msg
     * @return
     */
    public static int readIcInfo(final DeviceCallback callback, EmvOptions options,
                                 final String[] wantTags, com.siecom.proto.Message.siecomproto msg,
                                 final boolean isOnMain) {
        String tagList = "";
        //解析传进来的标签
        try {
            JSONObject jsonObject = new JSONObject(msg.getRequest());
            if(jsonObject.has("tagList")){
               tagList = jsonObject.getString("tagList");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        LogUtil.e(TAG,"P350 开始读IC卡 ");
        String finalTagList = tagList;
        SiecomDevice.ReadBankCard(0, null, new SiecomTask.TaskCallback() {
            @Override
            public void onStart(Bundle bundle) {
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        // 11键盘  10指纹 9IC卡  8磁条卡  5蓝牙 6 身份证
                        MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)1);
                        MainActivity.startInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        // 11键盘  10指纹 9IC卡  8磁条卡  5蓝牙 6 身份证
                        MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)1);
                        MainActivity.startNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.startSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:

                        MainActivity.startInoneCard();
                        break;

                }
            }

            @Override
            public void onSucceed(Bundle bundle) {
                BankCardInfoBean data = bundle.getParcelable("data");
                LogUtil.e(TAG,"onSucceed data == " + data.toString());
                com.siecom.bean.BankCardInfoBean bean = new com.siecom.bean.BankCardInfoBean();
                bean.cardNo = data.cardNo;
                bean.cardType = data.cardType;
                bean.setICChipData(data.ICChipData);
                parseAndSetCardInfo(finalTagList,bean); //设置数据
                Bundle bund = new Bundle();
                bund.putParcelable("data",bean);
                callback.onSuccess(bund);
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.stopInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.stopNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.stopSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.stopInoneCard();
                        break;

                }
                // 11键盘  10指纹 9IC卡  8磁条卡  5蓝牙 6 身份证
                MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)0);
                MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)0);
            }

            @Override
            public void onError(Bundle bundle) {
                LogUtil.e(TAG,"onError data == " + bundle.getInt("code"));
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.stopInsideCard();

                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.stopNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.stopSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.stopInoneCard();
                        break;

                }
                callback.onError(bundle);
                // 11键盘  10指纹 9IC卡  8磁条卡  5蓝牙 6 身份证
                MainActivity.getmSys().DLL_SysLedControl((byte) 9,(byte)0);
                MainActivity.getmSys().DLL_SysLedControl((byte) 8,(byte)0);
            }
        },msg.getTimeout());
        return 0;
    }

    /**
     * 自动获取card
     *
     * @param callback
     * @param
     * @return
     */
    public static int autoCardInfo(final DeviceCallback callback, EmvOptions options, String[] wantTags, com.siecom.proto.Message.siecomproto msg, final boolean isOnMain) {

        String tagList = "";
        //解析传进来的标签
        try {
            JSONObject jsonObject = new JSONObject(msg.getRequest());
            if(jsonObject.has("tagList")){
               tagList = jsonObject.getString("tagList");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        String finalTagList = tagList;
        SiecomDevice.ReadBankCard(BankCardModule.AUTO_FIND, null, new SiecomTask.TaskCallback() {
            @Override
            public void onStart(Bundle bundle) {
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.startInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.startNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.startSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.startInoneCard();
                        break;

                }
            }

            @Override
            public void onSucceed(Bundle bundle) {
                BankCardInfoBean data = bundle.getParcelable("data");
                LogUtil.e(TAG,"onSucceed data == " + data.toString());
                com.siecom.bean.BankCardInfoBean bean = new com.siecom.bean.BankCardInfoBean();
                bean.cardNo = data.cardNo;
                bean.cardType = data.cardType;
                bean.setICChipData(data.ICChipData);
                parseAndSetCardInfo(finalTagList,bean);
                Bundle bund = new Bundle();
                bund.putParcelable("data",bean);
                callback.onSuccess(bund);
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.stopInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.stopNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.stopSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.stopInoneCard();
                        break;

                }
            }

            @Override
            public void onError(Bundle bundle) {
                LogUtil.e(TAG,"onError data == " + bundle.getInt("code"));
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.stopInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.stopNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.stopSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.stopInoneCard();
                        break;

                }
                callback.onError(bundle);
            }
        },msg.getTimeout());

        return 0;
    }

    public static void cancelFinancial() {
        if (financialRunnable != null) {
            financialRunnable.stopRun();
            financialRunnable = null;

        }
        SiecomDevice.cancelLastTask(true);
        MainActivity.stopNfcCard();
        MainActivity.stopInsideCard();
        MainActivity.stopInoneCard();
    }

    /**
     * 刷磁条卡
     *
     * @param callback
     * @param
     * @return
     */
    public static int readMsr(final DeviceCallback callback, EmvOptions options, com.siecom.proto.Message.siecomproto msg, final boolean isOnMain) {

        SiecomDevice.ReadBankCard(2, null, new SiecomTask.TaskCallback() {
            @Override
            public void onStart(Bundle bundle) {
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.startInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.startNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.startSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.startInoneCard();
                        break;
                }
                callback.onStart();
            }

            @Override
            public void onSucceed(Bundle bundle) {
                BankCardInfoBean data = bundle.getParcelable("data");
                LogUtil.e(TAG,"onSucceed data == " + data.toString());
                com.siecom.bean.BankCardInfoBean bean = new com.siecom.bean.BankCardInfoBean();
                bean.cardNo = data.cardNo;
                bean.cardType = 1; //磁条卡
                bean.setICChipData(data.ICChipData);
                bean.oneMagneticTrack = data.oneMagneticTrack;
                bean.twoMagneticTrack = data.twoMagneticTrack;
                bean.threeMagneticTrack = data.threeMagneticTrack;
                Bundle bund = new Bundle();
                bund.putParcelable("data",bean);
                callback.onSuccess(bund);
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.stopInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.stopNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.stopSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.stopInoneCard();
                        break;

                }
            }

            @Override
            public void onError(Bundle bundle) {
                LogUtil.e(TAG,"onError data == " + bundle.getInt("code"));
                switch (msg.getCmd()) {
                    case ConstDefine.IC_REQUEST:
                        MainActivity.stopInsideCard();
                        break;
                    case ConstDefine.PIC_REQUEST:
                        MainActivity.stopNfcCard();
                        break;
                    case ConstDefine.MSR_REQUEST:
                        MainActivity.stopSwipeCard();
                        break;
                    case ConstDefine.AUTO_REQUEST:
                        MainActivity.stopInoneCard();
                        break;
                }

                callback.onError(bundle);
            }
        },msg.getTimeout());

        return 0;
    }


    /********************************金融模块结束*****************************************/



    public static void cancelIdentity() {

        SiecomDevice.cancelLastTask(true);
        MainActivity.stopIDAnime();
        MainActivity.playVoice(ConstDefine.OPERATE_FAIL);
    }


    /************************************
     * 身份证模块结束
     *************************************/


    protected static synchronized void deliverResult(final DeviceCallback callback, Result result, Bundle bundle, boolean onMainThread) {
        if (onMainThread) {
            handler.setCallback(callback);
            if (result == Result.SUCCEED) {
                Message msg = new Message();
                msg.what = SUCCESS;
                msg.setData(bundle);
                handler.sendMessage(msg);
            } else if (result == Result.ERROR) {
                Message msg = new Message();
                msg.what = ERROR;
                msg.setData(bundle);
                handler.sendMessage(msg);
            } else if (result == Result.COMPLETED) {
                Message msg = new Message();
                msg.what = COMPLETED;
                msg.setData(bundle);
                handler.sendMessage(msg);
            } else if (result == Result.START) {
                Message msg = new Message();
                msg.what = START;
                handler.sendMessage(msg);
            }
        } else {
            if (result == Result.SUCCEED) {
                callback.onSuccess(bundle);
            } else if (result == Result.ERROR) {
                callback.onError(bundle);
            } else if (result == Result.COMPLETED) {
                callback.onCompleted(bundle);
            } else if (result == Result.START) {
                callback.onStart();
            }
        }

    }

    private static class CallBackHandler extends Handler {
        private DeviceCallback callback;

        public CallBackHandler() {

            super(Looper.getMainLooper());
        }

        public void setCallback(DeviceCallback callback) {
            this.callback = callback;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START: {
                    callback.onStart();
                    break;
                }
                case SUCCESS: {
                    Bundle bundle = msg.getData();
                    callback.onSuccess(bundle);
                    break;
                }
                case ERROR: {
                    Bundle bundle = msg.getData();
                    callback.onError(bundle);
                    break;
                }
                case COMPLETED: {
                    Bundle bundle = msg.getData();
                    callback.onCompleted(bundle);
                    break;
                }
            }

        }

    }

    public static void showToast(String message) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.context, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private static boolean tryOpenMAC(WifiManager manager) {
        boolean softOpenWifi = false;
        int state = manager.getWifiState();
        if (state != WifiManager.WIFI_STATE_ENABLED && state != WifiManager.WIFI_STATE_ENABLING) {
            manager.setWifiEnabled(true);
            softOpenWifi = true;
        }
        return softOpenWifi;
    }

    //尝试关闭MAC
    private static void tryCloseMAC(WifiManager manager) {
        manager.setWifiEnabled(false);
    }

    //尝试获取MAC地址
    private static String tryGetMAC(WifiManager manager) {
        WifiInfo wifiInfo = manager.getConnectionInfo();
        if (wifiInfo == null || wifiInfo.getMacAddress() == null) {
            return null;
        }
        String mac = wifiInfo.getMacAddress().replaceAll(":", "").trim().toUpperCase();
        LogUtil.e(TAG,"tryGetMAC=" + mac);
        return mac;
    }

    //尝试读取MAC地址
    public static String getMacFromDevice() {
        String mac = null;
        WifiManager wifiManager = (WifiManager) MainActivity.context.getSystemService(Context.WIFI_SERVICE);
        mac = tryGetMAC(wifiManager);
        LogUtil.e(TAG,"第一次获取Mac=" + mac);

        if (mac != null) {
            return mac;
        }

        //获取失败，尝试打开wifi获取
        boolean isOkWifi = false;
        for (int i = 0; i < 3; i++) {
            isOkWifi = tryOpenMAC(wifiManager);
            if (isOkWifi) {
                break;
            }
            SystemClock.sleep(100);
        }


        for (int index = 0; index < 10; index++) {
            //如果第一次没有成功，第二次做100毫秒的延迟。
            if (index != 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            mac = tryGetMAC(wifiManager);
            LogUtil.e(TAG,"第二次获取Mac=" + mac);
            if (mac != null) {
                break;
            }
        }

        //尝试关闭wifi
        if (isOkWifi) {
            tryCloseMAC(wifiManager);
        }
        return mac;
    }


    public static void parseAndSetCardInfo(String tagList,com.siecom.bean.BankCardInfoBean bean){
        LogUtil.e(TAG,"tagList == " + tagList);
        String icChipData = bean.getICChipData();
        if (TextUtils.isEmpty(icChipData)) return;
        String tag5A = StringUtil.tagParse("5A",icChipData); //A 41 卡号
        LogUtil.e(TAG,"tag5A=" + tag5A);
        String tag5f20 = StringUtil.tagParse("5F20",icChipData); // B 42姓名
        LogUtil.e(TAG,"tag5f20=" + tag5f20);


        String tag9F61 = StringUtil.tagParse("9F61",icChipData);//D 44 证件号码
        LogUtil.e(TAG,"tag9F61=" + tag9F61);
        String tag9F62 = StringUtil.tagParse("9F62",icChipData); // C 43 证件类型
        LogUtil.e(TAG,"tag9F62=" + tag9F62);
        String tag9F1F = StringUtil.tagParse("9F1F",icChipData); // F 一磁道信息
        LogUtil.e(TAG,"tag9F1F=" + tag9F1F);
        String track2Str = StringUtil.tagParse(tag5A.length() + 4,"57",icChipData); //E 二磁道信息
        LogUtil.e(TAG,"track2Str 57 =" + track2Str);
        String tag9F77 = StringUtil.tagParse("9F77",icChipData);//H 余额上线
        LogUtil.e(TAG,"tag9F1F=" + tag9F77);
        String tag9F79 = StringUtil.tagParse("9F79",icChipData);//G 余额
        LogUtil.e(TAG,"tag9F79=" + tag9F79);
        String tag5F24 = StringUtil.tagParse("5F24",icChipData);//I 失效日期
        LogUtil.e(TAG,"tag5F24=" + tag5F24);
        String tag5F34 = StringUtil.tagParse("5F34",icChipData);//J 序列号
        LogUtil.e(TAG,"tag5F34=" + tag5F34);
        String tag5F2A = StringUtil.tagParse("5F2A",icChipData);// 交易货币代码
        LogUtil.e(TAG,"tag5f2A=" + tag5F2A);
        String tag9F78 = StringUtil.tagParse("9F78",icChipData);//单笔交易限额
        LogUtil.e(TAG,"tag9F78=" + tag9F78);

        StringBuilder sb = new StringBuilder();
        if(!TextUtils.isEmpty(tagList) && !tagList.contains("ALL")){
            if(tagList.contains("A")) //0x41 卡号
                sb.append("A").append(getStrLength(tag5A)).append(tag5A);
            if(tagList.contains("B")) // 姓名
                sb.append("B").append(getStrLength(tag5f20)).append(tag5f20);
            if(tagList.contains("C")) // 证件类型
                sb.append("C").append(getStrLength(tag9F62)).append(tag9F62);
            if(tagList.contains("D")) // 证件号码
                sb.append("D").append(getStrLength(tag9F61)).append(tag9F61);
            if(tagList.contains("E")) // 余额
                sb.append("E").append(getStrLength(tag9F79)).append(tag9F79);
            if(tagList.contains("F")) // 余额上限
                sb.append("F").append(getStrLength(tag9F77)).append(tag9F77);
            if(tagList.contains("G")) // 单笔交易限额
                sb.append("G").append(getStrLength(tag9F78)).append(tag9F78);
            if(tagList.contains("H")) // 交易货币代码
                sb.append("H").append(getStrLength(tag5F2A)).append(tag5F2A);
            if(tagList.contains("I")) // 失效日期
                sb.append("I").append(getStrLength(tag5F24)).append(tag5F24);
            if(tagList.contains("J")) // IC卡序列号
                sb.append("J").append(getStrLength(tag5F34)).append(tag5F34);
            if(tagList.contains("K")) // 二磁道信息
                sb.append("K").append(getStrLength(track2Str)).append(track2Str);
            if(tagList.contains("L")) // 一磁道信息
                sb.append("L").append(getStrLength(tag9F1F)).append(tag9F1F);
        }else {
                sb.append("A").append(getStrLength(tag5A)).append(tag5A);
                sb.append("B").append(getStrLength(tag5f20)).append(tag5f20);
                sb.append("C").append(getStrLength(tag9F62)).append(tag9F62);
                sb.append("D").append(getStrLength(tag9F61)).append(tag9F61);
                sb.append("E").append(getStrLength(tag9F79)).append(tag9F79);
                sb.append("F").append(getStrLength(tag9F77)).append(tag9F77);
                sb.append("G").append(getStrLength(tag9F78)).append(tag9F78);
                sb.append("H").append(getStrLength(tag5F2A)).append(tag5F2A);
                sb.append("I").append(getStrLength(tag5F24)).append(tag5F24);
                sb.append("J").append(getStrLength(tag5F34)).append(tag5F34);
                sb.append("K").append(getStrLength(track2Str)).append(track2Str);
                sb.append("L").append(getStrLength(tag9F1F)).append(tag9F1F);
        }

        bean.twoMagneticTrack = track2Str;
        bean.serialNo = tag5F34; //序列号
        bean.tagListInfo = sb.toString();
        LogUtil.e(TAG,"outDataStr == " + sb.toString());
    }
    private static String getStrLength(String str){
        return String.format("%03d", str.length());
    }
}
